import { useEffect, useState } from 'react'
import { ExtendedApiClient } from '@/lib/api'
import { getApiClient, getApiClientInfo } from '@/lib/apiClientFactory'
import { useDevToolsStore } from '@/stores/devToolsStore'

// 使用API客户端的Hook
export const useApiClient = () => {
    const [apiClient, setApiClient] = useState<ExtendedApiClient>(() => getApiClient())
    const { useMockApi, mockDataMode } = useDevToolsStore()

    // 当开发工具设置变化时，更新API客户端
    useEffect(() => {
        const newClient = getApiClient()
        setApiClient(newClient)
    }, [useMockApi, mockDataMode])

    return apiClient
}

// 获取API客户端信息的Hook
export const useApiClientInfo = () => {
    const [clientInfo, setClientInfo] = useState(() => getApiClientInfo())
    const { useMockApi, mockDataMode, isEnabled } = useDevToolsStore()

    useEffect(() => {
        setClientInfo(getApiClientInfo())
    }, [useMockApi, mockDataMode, isEnabled])

    return clientInfo
}

// 带有重试功能的API调用Hook
export const useApiCall = <T>(
    apiCall: () => Promise<T>,
    dependencies: any[] = []
) => {
    const [data, setData] = useState<T | null>(null)
    const [loading, setLoading] = useState(false)
    const [error, setError] = useState<Error | null>(null)
    const apiClient = useApiClient()

    const execute = async () => {
        setLoading(true)
        setError(null)

        try {
            const result = await apiCall()
            setData(result)
        } catch (err) {
            setError(err instanceof Error ? err : new Error('Unknown error'))
        } finally {
            setLoading(false)
        }
    }

    useEffect(() => {
        execute()
    }, [apiClient, ...dependencies])

    return {
        data,
        loading,
        error,
        refetch: execute
    }
}

export default useApiClient